<?php

namespace app\common\behavior;

use fast\Http;
use think\Cache;
use think\Db;
use think\Log;

class Ad
{

    /**
     * @param $param
     * @param $data
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function tfStatistics(&$param,$datas)
    {
        // 默认值
        $type = false;
        $goodsId = 0;
        $appid = '';
        $source = '巨量';

        // 解析
        extract($param);
        extract($datas);
        $time = time();
        $sourceArr = ['巨量','腾讯','变现猫','磁力'];
        $cache = Cache::store('redis');
        // 设置昨天的标识
        $setYesterDay = date('Ymd');
        if (!$cache->has($setYesterDay)){
            $cache->set($setYesterDay,'yesterday');
        }

        $data = [];

        if ($clickId){
            // 根据 $clickId $eventType 确定记录是否存在
            $data = Db::name('ad_tf_log')->where(['clickid'=>$clickId,'event_type'=>$eventType])->find();
        }

        if ($clickId && empty($data) && !$type){
            // 新增数据
            Db::name('ad_tf_log')->insert([
                'goods' => $goodsId,
                'source' => $source,
                'clickid' => $clickId,
                'event_type' => $eventType,
                'appid' => $appid,
                'state' => 0,
                'createtime' => $time,
            ]);

            $key = 'clicknum'.date('Ymd') .'_'. $source;
            if ($cache->has($key)){
                $cache->inc($key);
            }else{
                $cache->set($key,1);
            }
        }

        if ($data && $type){
            // 修改数据
            Db::name('ad_tf_log')->where(['clickid'=>$clickId,'event_type'=>$eventType])->update([
                'state' => 1,
                'updatetime' => $time,
            ]);

            $key = 'tfnum'.date('Ymd') .'_'. $data['source'];
            if ($cache->has($key)){
                $cache->inc($key);
            }else{
                $cache->set($key,1);
            }
        }

        $yesterday = date('Ymd',bcsub($time,86400));
        if ($cache->has($yesterday)){
            $All = [];
            foreach ($sourceArr as $str){
                $All[] = [
                    'date' => $yesterday,
                    'clicknum' => $cache->get('clicknum'. $yesterday .'_'. $str),
                    'tfnum' => $cache->get('tfnum'. $yesterday .'_'. $str),
                    'createtime' => $time,
                    'platform' => $str
                ];
                // 删除之前的记录
                $cache->rm('clicknum'. $yesterday .'_'. $str);
                $cache->rm('tfnum'. $yesterday .'_'. $str);
            }
            if ($All){
                Db::name('ad_tf_statistics')->insertAll($All);
                // 删除yesterday
                $cache->rm($yesterday);
            }
        }


    }

    public function tfSend(&$param,$datas)
    {
        // 解析数据
        extract($param);
        extract($datas);
        // 订单ID 必传
//        $order_id = $param['order_id'];
        // 查询订单记录
        $order = Db::name("wanlshop_order")->where('id',$order_id)->find();

        if ($order){
            $clickid = $order['event_type']??'';
            $event_type = $order['event']?:'customer_effective';
            if (strpos($event_type,'event_type') !== false){
                $event_type = substr($event_type,10);
            }

            Log::error($clickid);
            Log::error($event_type);
            $params = [
                'clickId' => $clickid,
                'eventType' => $event_type,
            ];
            $data = [
                "type" => true,
            ];
            // $clickid 字符串匹配判断 clickid:巨量
            // $clickid 字符串匹配判断 qz_gdt:腾讯
            // $clickid 字符串匹配判断 bxmid:变现猫
            // $clickid 字符串匹配判断 cili:磁力
            if (strpos($clickid, 'clickid') !== false){
                // 巨量
                $clickid = substr($clickid, 7);
                $this->tfStatistics($params,$data);
                $time = time() * 1000;

                $data = '{
                    "event_type": "'.$event_type.'",
                    "context":
                    {
                        "ad": {"callback": "'.$clickid.'"}
                    },
                    "timestamp": '.$time.'
                }';
                Log::error($data);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "https://analytics.oceanengine.com/api/v2/conversion");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                ));
                $result = curl_exec($ch);
                curl_close($ch);
                Log::error($result);
                return $result;
            }
            if (strpos($clickid, 'qz_gdt') !== false){
                $clickid = substr($clickid, 6);
                $this->tfStatistics($params,$data);
                // 腾讯
                $data = [
                    "clickid" => $clickid,
                    "action_time" => time(),
                    "action_type" => $event_type,
                    "link" => $_SERVER['HTTP_HOST'],
                ];

                $result = Http::get("https://tracking.e.qq.com/conv/web",$data);
                return $result;
            }
            if (strpos($clickid, 'bxmid') !== false){
                $clickid = substr($clickid, 5);
                $this->tfStatistics($params,$data);
                // 变现猫
                $data = [
                    "mt" => 8,
                    "bxmid" => $clickid,
                    "conversion_type" => $event_type,
                ];

                $result = Http::get("https://openlog.bianxianmao.com/inads/s.gif",$data);
                return $result;
            }
            if (strpos($clickid, 'cili') !== false){
                $clickid = substr($clickid, 4);
                $this->tfStatistics($params,$data);
                // 磁力
                $callback = $clickid;
                list($mt1,$mt2) = explode(' ', microtime());
                $event_time = (int)($mt1 * 1000);
                $purchase_amount = Db::name('wanlshop_pay')->where(['order_id'=>$order_id,'state'=>'1'])->value('actual_payment');

                $data = [
                    "callback" => $callback,
                    "event_time" => $event_time,
                    "event_type" => $event_type,
                    "purchase_amount" => $purchase_amount,
                ];

                $result = Http::get("https://ad.partner.gifshow.com/track/activate",$data);
                return $result;
            }
        }else{
            return false;
        }

        return true;
    }
}